package com.zretc.config;

import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

/**
 * @author 周文涛
 * 文件上传配置类
 */
public class FastDFSUtils {

    private static StorageClient1 client1;

    public static final String IMG_ADDRESS = "http://localhost:8081/download/?address=";

    static {
        try {
            ClientGlobal.initByProperties("fastdfs-client.properties");
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            client1 = new StorageClient1(trackerServer, null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

    public static String upload(MultipartFile file) {
        String oldName = file.getOriginalFilename();
        try {
            return client1.upload_file1(file.getBytes(), oldName.substring(oldName.lastIndexOf(".") + 1), null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void download(HttpServletResponse response,String address){
        response.setContentType("image/jpeg");
        try {
            byte[] bytes = client1.download_file1(address);

            // 字节数组输出流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bos.write(bytes,0,bytes.length);

            ServletOutputStream ops = response.getOutputStream();
            ops.write(bos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

    public static void deleteFile(String address){
        String replace = address.replace(IMG_ADDRESS, "");
        try {
            client1.delete_file1(replace);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }
}
